<?php
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
if (!class_exists("ParseIni"))
{
    require_once(CLASS_PARSE_INI);
}

/**
 * Class::BigDaddy::BigDaddyData
 * Main classes for setting BigDaddy control to the BigDaddy Database
 * @author Duleepa Wijayawardhana <dups@bioware.com>
 * @version 30/05/2006 11:38:06
 */
class BigDaddyControl extends BigDaddy
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * SetCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 10:42:00 2006
     *
     * Sets a Server Category
     */
    public function SetServerCategory($sCategoryName, $nID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nID == NULL)
        {
            $sql="INSERT INTO server_category SET
                name='".htmlspecialchars($sCategoryName)."'";
            $nInsertID = db_query($sql, array("getInsertID" => true));
            
            $aOptions=array(
                "primaryNumericID" => $nInsertID,
                "type" => "server_category_edit",
                "action" => __METHOD__,
                "comment" => "Added New Server CategoryID $nInsertID with name $sCategoryName"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
        else
        {
            $sql="UPDATE server_category SET
                name='".htmlspecialchars($sCategoryName)."'
                WHERE ID='".$nID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "server_category_edit",
                "action" => __METHOD__,
                "comment" => "Updated Server CategoryID $nInsertID with name $sCategoryName"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
        
    }
    /**
     * RemoveCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 10:43:42 2006
     *
     * Removes a category
     */
    public function RemoveServerCategory($nID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="DELETE FROM server_category WHERE ID='".$nID."'";
        db_query($sql);
            
        $sql="DELETE FROM server_category_map WHERE categoryID='".$nID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nID,
            "type" => "server_category_edit",
            "action" => __METHOD__,
            "comment" => "Removed ServerCategoryID $nID"
        );
        $this->Audit->SetAudit($aOptions, "server");
        
    }
    /**
     * SetServer
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 10:47:43 2006
     *
     * Sets A Server
     */
    public function SetServer($aInfo, $nServerID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nServerID == NULL)
        {
            $sql="INSERT INTO server SET
                hostname='".$aInfo["hostname"]."',
            	iniID='".$aInfo["iniID"]."',
            	mon_startlevel='".$aInfo["mon_startlevel"]."',
            	mon_endlevel='".$aInfo["mon_endlevel"]."',
            	mon_internalreport='".$aInfo["mon_internalreport"]."',
            	mon_externalreport='".$aInfo["mon_externalreport"]."',
            	os_type = '".$aInfo["os_type"]."',
                notes='".$aInfo["notes"]."'";
            $insertID=db_query($sql, array("getInsertID" => true));
            
            $this->SetServerCategoryMap($insertID, $aInfo["cat"]);
            
            $aOptions=array(
                "primaryNumericID" => $insertID,
                "type" => "server_edit",
                "action" => __METHOD__,
                "comment" => "Inserted New Server ID $insertID hostname: ".$aInfo["hostname"]
            );
            $this->Audit->SetAudit($aOptions, "server");
            
            return $insertID;
        }
        else
        {
            $sql="UPDATE server SET
                hostname='".$aInfo["hostname"]."',
                iniID='".$aInfo["iniID"]."',
                mon_startlevel='".$aInfo["mon_startlevel"]."',
                mon_endlevel='".$aInfo["mon_endlevel"]."',
                mon_internalreport='".$aInfo["mon_internalreport"]."',
                mon_externalreport='".$aInfo["mon_externalreport"]."',
                os_type = '".$aInfo["os_type"]."',
                notes='".$aInfo["notes"]."'
                WHERE ID='".$nServerID."'";
            db_query($sql);
            
            
            $this->RemoveFromServerCategoryMap($nServerID);
            $this->SetServerCategoryMap($nServerID, $aInfo["cat"]);
            
            $aOptions=array(
                "primaryNumericID" => $nServerID,
                "type" => "server_edit",
                "action" => __METHOD__,
                "comment" => "Updated Server ID $nServerID hostname: ".$aInfo["hostname"]
            );
            $this->Audit->SetAudit($aOptions, "server");

        }

    }
    /**
     * SetServerCategoryMap
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    private function SetServerCategoryMap($nServerID, $aCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        if (is_array($aCatID))
        {
            foreach ($aCatID as $nCatID)
            {
                $sql="INSERT INTO server_category_map SET
                    serverID='".$nServerID."',
                    categoryID='".$nCatID."'";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nServerID,
                    "type" => "server_edit",
                    "action" => __METHOD__,
                    "comment" => "Added ServerID $nServerID to CategoryID $nCatID"
                );
                $this->Audit->SetAudit($aOptions, "server");
            }
        }
        
        
    }
    /**
     * RemoveFromServerCategoryMap
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    public function RemoveFromServerCategoryMap($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        $sql="DELETE FROM server_category_map WHERE serverID='".$nServerID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Removed Server ID $nServerID from all categories"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerStatusEnabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:40:31 2006
     */
    public function SetServerStatusEnabled($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="UPDATE server SET
            active=1,
            delayed_until='',
            last_monenabled=".time()."
            WHERE ID='".$nServerID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Enabled Server $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:40:31 2006
     */
    public function SetServerStatusDisabled($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="UPDATE server SET
            active=0,
            delayed_until='',
            mon_currentlevel=0,
            mon_currentlevelstart=0,
            mon_lastcheck=0
            WHERE ID='".$nServerID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Disabled Server $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * RemoveServer
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:40:31 2006
     */
    public function RemoveServer($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="DELETE FROM server WHERE ID='".$nServerID."'";
        $delete=run_mysql_query($sql);
        
        $this->RemoveFromServerCategoryMap($nServerID);
        
        $this->RemoveServerModulesByServer($nServerID);
        
        $this->RemoveServerGroupModuleByServerID($nServerID);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Removed ServerID $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
			
    }
    /**
     * RemoveServerModulesByServer
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    public function RemoveServerModulesByServer($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        $sql="DELETE FROM server_module WHERE serverID='".$nServerID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Removed All Modules from serverID  $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerStatusEnabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    public function SetServerStatusEnabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        $sql="SELECT serverID FROM server_category_map WHERE categoryID='".$nCatID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            foreach ($aResult as $aRow)
            {
                $aServer[] = $aRow["serverID"];
                
                $aOptions=array(
                    "primaryNumericID" => $aRow["serverID"],
                    "type" => "server_edit",
                    "action" => __METHOD__,
                    "comment" => "Enabled Server ".$aRow["serverID"]
                );
                $this->Audit->SetAudit($aOptions, "server");
            }
                   
            $sql="UPDATE server SET
                active=1,
                delayed_until='',
                last_monenabled=".time()."
                WHERE ID IN (".join($aServer, ",").")";
                db_query($sql);
                
            $aOptions=array(
                "primaryNumericID" => $nCatID,
                "type" => "server_category_edit",
                "action" => __METHOD__,
                "comment" => "Enabled Servers in Category $nCatID (".join($aServer, ",").")"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
    }
    /**
     * SetServerStatusDisabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    public function SetServerStatusDisabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        $sql="SELECT serverID FROM server_category_map WHERE categoryID='".$nCatID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            foreach ($aResult as $aRow)
            {
                $aServer[] = $aRow["serverID"];
                
                $aOptions=array(
                    "primaryNumericID" => $aRow["serverID"],
                    "type" => "server_edit",
                    "action" => __METHOD__,
                    "comment" => "Disabled Server ".$aRow["serverID"]
                );
                $this->Audit->SetAudit($aOptions, "server");
            }
            
            $sql="UPDATE server SET
                active=0,
                delayed_until='',
                mon_currentlevel=0,
                mon_currentlevelstart=0,
                mon_lastcheck=0
                WHERE ID IN (".join($aServer, ",").")";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCatID,
                "type" => "server_category_edit",
                "action" => __METHOD__,
                "comment" => "Disabled Servers in Category $nCatID (".join($aServer, ",").")"
            );
            $this->Audit->SetAudit($aOptions, "server");
            
        }
    }
    /**
     * SetServerStatusDelayed
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:40:31 2006
     */
    public function SetServerStatusDelayed($nServerID, $nDelayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nDelayUntil > time())
        {
            $sql="UPDATE server SET
                active=2,
                delayed_until='".$nDelayUntil."'
                WHERE ID='".$nServerID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nServerID,
                "type" => "server_edit",
                "action" => __METHOD__,
                "comment" => "Delayed Server $nServerID until UNIX_TIMESTAMP $nDelayUntil"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
    }
    /**
     * SetServerStatusDelayedByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 12:17:29 2006
     */
    public function SetServerStatusDelayedByCategory($nCatID, $nDelayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;

        if ($nDelayUntil > time())
        {
            $sql="SELECT m.serverID
                FROM server_category_map m
                LEFT JOIN server s ON s.ID=m.serverID
                WHERE s.active=1
                    AND m.categoryID='".$nCatID."'";
            $aResult=db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $aRow)
                {
                    $aServer[] = $aRow["serverID"];
                    $aOptions=array(
                        "primaryNumericID" => $aRow["serverID"],
                        "type" => "server_edit",
                        "action" => __METHOD__,
                        "comment" => "Delayed Server ".$aRow["serverID"]." until UNIX_TIMESTAMP $nDelayUntil"
                    );
                    $this->Audit->SetAudit($aOptions, "server");
                }
                
                $sql="UPDATE server SET
                    active=2,
                    delayed_until='".$nDelayUntil."'
                    WHERE ID IN (".join($aServer, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "server_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Delayed Servers in Category $nCatID (".join($aServer, ",").") until UNIX_TIMESTAMP $nDelayUntil"
                );
                $this->Audit->SetAudit($aOptions, "server");
                
            }
        }
    }
    /**
     * SetGlobalServerStatusNormal
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 13:52:41 2006
     */
    public function SetGlobalServerStatusNormal()
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $parseini=new ParseIni("servermon");
		$globalSettings=$parseini->read_inifile();
		
        $parseini->write_inivar("[global]globalstatus=on");
        $parseini->write_inivar("[global]globaldelay=0");
        $parseini->writetoDB();
		
		//If the status previously was off or delayed then we need to prevent monitoring from being stale.
		if ($globalSettings["global"]["globalstatus"]=="off" || $globalSettings["global"]["globalstatus"]=="delay")
		{
			$sql="UPDATE server SET
                last_monenabled=".time().",
                mon_currentlevel=0,
                mon_lastcheck=0,
                mon_currentlevelstart=0
            WHERE active=1";
			db_query($sql);
		}
        
        $aOptions=array(
            "type" => "server_global",
            "action" => __METHOD__,
            "comment" => "Enabled all Servers Globally"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetGlobalServerStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 13:52:41 2006
     */
    public function SetGlobalServerStatusDisabled()
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $parseini=new ParseIni("servermon");
        $parseini->write_inivar("[global]globalstatus=off");
        $parseini->write_inivar("[global]globaldelay=0");
        $parseini->writetoDB();
        
        $aOptions=array(
            "type" => "server_global",
            "action" => __METHOD__,
            "comment" => "Disabled all Servers Globally"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetGlobalServerStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 13:52:41 2006
     */
    public function SetGlobalServerStatusDelayed($nDelayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nDelayUntil>time())
        {
            $parseini=new ParseIni("servermon");
            $parseini->write_inivar("[global]globalstatus=delay");
            $parseini->write_inivar("[global]globaldelay=".$nDelayUntil);
            $parseini->writetoDB();
            
            $aOptions=array(
                "type" => "server_global",
                "action" => __METHOD__,
                "comment" => "Delayed all Servers Globally until UNIX_TIMESTAMP: $nDelayUntil"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
    }
    /**
     * SetServerMod
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 13:57:22 2006
     */
    public function SetServerMod($aInfo, $nModID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($aInfo["serverID"]>0 && $aInfo["modID"]>0 && $aInfo["iniID"]!="")
        {
            if ($nModID == NULL)
            {
            
                $sql="INSERT INTO server_module SET
                    serverID='".$aInfo["serverID"]."',
                    moduleID='".$aInfo["modID"]."',
                    iniID='".$aInfo["iniID"]."',
                    mon_startlevel='".$aInfo["mon_startlevel"]."',
                    lastreport_threshold='".$aInfo["lastreport_threshold"]."',
                    mon_endlevel='".$aInfo["mon_endlevel"]."',
                    parameters='".$aInfo["parameters"]."'";
                    $nInsertID = db_query($sql, array("getInsertID" => true));
                    
                    $aOptions=array(
                        "primaryNumericID" => $aInfo["serverID"],
                        "secondaryNumericID" => $nInsertID,
                        "type" => "server_edit",
                        "action" => __METHOD__,
                        "comment" => "Updated Server ID ".$aInfo["serverID"]." with new Server ModuleID $nInsertID (of type ".$aInfo["modID"]
                    );
                    $this->Audit->SetAudit($aOptions, "server");
            }
            else
            {
                $sql="UPDATE server_module SET
                    iniID='".$aInfo["iniID"]."',
                    mon_startlevel='".$aInfo["mon_startlevel"]."',
                    lastreport_threshold='".$aInfo["lastreport_threshold"]."',
                    mon_endlevel='".$aInfo["mon_endlevel"]."',
                    parameters='".$aInfo["parameters"]."'
                WHERE ID='".$nModID."'";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $aInfo["serverID"],
                    "secondaryNumericID" => $nModID,
                    "type" => "server_edit",
                    "action" => __METHOD__,
                    "comment" => "Updated Server ModuleID $nInsertID on Server ID ".$aInfo["serverID"].". Array of changes: ".print_r($aInfo, true)
                );
                $this->Audit->SetAudit($aOptions, "server");
            }
        }
    }
    /**
     * SetServerModStatusEnabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:08:10 2006
     */
    public function SetServerModStatusEnabled($nServerModuleID, $nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="UPDATE server_module SET
            active=1,
            delayed_until=0,
            mon_currentlevel=0,
            mon_currentlevelstart=0,
            last_monmodenabled='".time()."'
            WHERE ID='".$nServerModuleID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "secondaryNumericID" => $nServerModuleID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Enabled Server Module $nServerModuleID on Server $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerModStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:08:10 2006
     */
    public function SetServerModStatusDisabled($nServerModuleID, $nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="UPDATE server_module SET
            active=0,
            delayed_until=0,
            mon_currentlevel=0,
            mon_currentlevelstart=0
            WHERE ID='".$nServerModuleID."'";
        db_query($sql);
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "secondaryNumericID" => $nServerModuleID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Disabled Server Module $nServerModuleID on Server $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * RemoveServerMod
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:08:10 2006
     */
    public function RemoveServerMod($nServerModuleID, $nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="DELETE FROM server_module WHERE ID='".$nServerModuleID."'";
        db_query($sql);
        
        $this->RemoveServerGroupModuleByModuleID($nServerModuleID);
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "secondaryNumericID" => $nServerModuleID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Removed ModuleID: $nServerModuleID from serverID  $nServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerModStatusDelayed
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:08:10 2006
     */
    public function SetServerModStatusDelayed($nServerModuleID, $nDelayUntil, $nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nDelayUntil > time())
        {
            $sql="UPDATE server_module SET
                active=2,
                delayed_until='".$nDelayUntil."'
                WHERE ID='".$nServerModuleID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nServerID,
                "secondaryNumericID" => $nServerModuleID,
                "type" => "server_edit",
                "action" => __METHOD__,
                "comment" => "Delayed Server Module $nServerModuleID on Server $nServerID until UNIX_TIMESTAMP $nDelayUntil"
            );
            $this->Audit->SetAudit($aOptions, "server");
        }
       
    }
    /**
     * SetServerModCopy
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:18:29 2006
     */
    public function SetServerModCopy($nOriginalServerID, $nNewServerID, $nServerModID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nOriginalServerID == "")
        {
            return;
        }
        
        if ($nNewServerID == "")
        {
            return;
        }
        
        if ($nServerModID == "")
        {
            return;
        }
        
        $sql="SELECT iniID, mon_startlevel, mon_endlevel, lastreport_threshold, parameters, moduleID
            FROM server_module
            WHERE ID=".$nServerModID;
	    $smInfo=db_fetch_result(db_query($sql));

	    $sql="INSERT INTO server_module SET
            moduleID=".$smInfo["moduleID"].",
            serverID=".$nNewServerID.",
            iniID='".$smInfo["iniID"]."',
            mon_startlevel=".$smInfo["mon_startlevel"].",
            mon_endlevel=".$smInfo["mon_endlevel"].",
            lastreport_threshold='".$smInfo["lastreport_threshold"]."',
            parameters='".$smInfo["parameters"]."'";
	    $nInsertID = db_query($sql, array("getInsertID" => true));
        
        $aOptions=array(
            "primaryNumericID" => $nNewServerID,
            "secondaryNumericID" => $nInsertID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Copied Module settings from  $nOriginalServerID to $nNewServerID with new ServerModuleID of $nInsertID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetServerModCopyAll
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:18:29 2006
     */
    public function SetServerModCopyAll($nOriginalServerID, $nNewServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        //Can I copy?
	    $sql="SELECT COUNT(*) as count FROM server_module WHERE serverID=".$nNewServerID;
	    $aCount = db_fetch_result(db_query($sql));
        
        if ($aCount["count"] > 0)
        {
            return;
        }
        $sql="CREATE TEMPORARY TABLE copymod (
            ID int(10) unsigned not null auto_increment,
            serverID int(10) unsigned not null default '0',
            moduleID int(10) unsigned not null default '0',
            iniID varchar(40) not null default '',
            mon_startlevel tinyint(1) unsigned not null default '0',
            mon_endlevel tinyint(1) unsigned not null default '0',
            lastreport_threshold varchar(100) not null default '',
            parameters varchar(150) not null default '',
            PRIMARY KEY (ID)
            )";
		db_query($sql);

		$sql="INSERT INTO copymod (moduleID, iniID, mon_startlevel, mon_endlevel, lastreport_threshold,parameters)
        SELECT moduleID, iniID, mon_startlevel, mon_endlevel, lastreport_threshold, parameters
        FROM server_module
        WHERE serverID=".$nOriginalServerID;
		db_query($sql);

		$sql="UPDATE copymod SET serverID=".$nNewServerID;
		db_query($sql);

		$sql="INSERT INTO server_module (serverID, moduleID, iniID, mon_startlevel, mon_endlevel, lastreport_threshold,parameters)
        SELECT serverID, moduleID, iniID, mon_startlevel, mon_endlevel, lastreport_threshold, parameters
        FROM copymod";
		db_query($sql);
        
        $sql = "TRUNCATE TABLE copymod";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nNewServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Copied ALL Module settings from  $nOriginalServerID to $nNewServerID"
        );
        $this->Audit->SetAudit($aOptions, "server");
    }
    /**
     * SetCronCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 14:49:21 2006
     */
    public function SetCronCategory($sCatName, $nCatID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nCatID == NULL)
        {
            $sql="INSERT INTO cron_category SET
                name='".htmlspecialchars($sCatName)."'";
            $nInsertID = db_query($sql, array("getInsertID" => true));
            
            $aOptions=array(
                "primaryNumericID" => $nInsertID,
                "type" => "cron_category_edit",
                "action" => __METHOD__,
                "comment" => "Added new cron category ID $nInsertID, Name $sCatName"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
        else
        {
            $sql="UPDATE cron_category SET
                name='".htmlspecialchars($sCatName)."' WHERE ID='".$nCatID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nInsertID,
                "type" => "cron_category_edit",
                "action" => __METHOD__,
                "comment" => "Updated cron category ID $nCatID, Name $sCatName"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * RemoveCronCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 16:04:18 2006
     */
    public function RemoveCronCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($nCatID >0)
        {
            $sql="DELETE FROM cron_category WHERE ID='".$nCatID."'";
            db_query($sql);

            $sql="DELETE FROM cron_category_map WHERE categoryID='".$nCatID."'";
            db_query($sql);
            
            $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Removed Cron Category ID $nCatID"
                );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetCron
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 16:23:44 2006
     */
    public function SetCron($aInfo, $nCronID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        if ($aInfo["filename"] != "")
        {
            if ($nCronID == NULL)
            {
                
                $sql="INSERT INTO cronjob SET
                    filename='".htmlspecialchars($aInfo["filename"])."',
                    serverID='".$aInfo["serverID"]."',
                    iniID='".$aInfo["iniID"]."',
                    mon_startlevel='".$aInfo["mon_startlevel"]."',
                    mon_endlevel='".$aInfo["mon_endlevel"]."',
                    mon_threshold='".$aInfo["mon_threshold"]."',
                    notes='".htmlspecialchars($aInfo["notes"])."'";
                    $insertID=db_query($sql, array("getInsertID" => true));
               
                $this->SetCronCategoryMap($aInfo["cat"],$insertID);
                
                $aOptions=array(
                    "primaryNumericID" => $insertID,
                    "type" => "cron_edit",
                    "action" => __METHOD__,
                    "comment" => "Added New Cron  $insertID, filename ".$aInfo["filename"]
                );
                $this->Audit->SetAudit($aOptions, "crontab");
                
                return $insertID;
                
            }
            else
            {
                $sql="UPDATE cronjob SET
                filename='".htmlspecialchars($aInfo["filename"])."',
                serverID='".$aInfo["serverID"]."',
                iniID='".$aInfo["iniID"]."',
                mon_startlevel='".$aInfo["mon_startlevel"]."',
                mon_endlevel='".$aInfo["mon_endlevel"]."',
                mon_threshold='".$aInfo["mon_threshold"]."',
                notes='".htmlspecialchars($aInfo["notes"])."'
                WHERE ID='".$nCronID."'";
                db_query($sql);
                
                $this->RemoveCronFromCategoryMap($nCronID);
                $this->SetCronCategoryMap($aInfo["cat"],$nCronID);
                
                $aOptions=array(
                    "primaryNumericID" => $nCronID,
                    "type" => "cron_edit",
                    "action" => __METHOD__,
                    "comment" => "Updated Cron  $nCronID, filename ".$aInfo["filename"]
                );
                $this->Audit->SetAudit($aOptions, "crontab");
                
            }
         }
        
        
    }
    /**
     * SetCronCategoryMap
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 16:26:34 2006
     */
    public function SetCronCategoryMap($aCatID, $nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if (is_array($aCatID))
        {
            foreach ($aCatID as $nCatID)
            {
                $sql="INSERT INTO cron_category_map SET cronID='".$nCronID."', categoryID='".$nCatID."'";
                db_query($sql);
            }
        }
        
        $aOptions=array(
            "primaryNumericID" => $nCronID,
            "type" => "cron_edit",
            "action" => __METHOD__,
            "comment" => "Added Cron $nCronID to the following category IDs".join($aCatID, ", ")
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * RemoveCronCategoryMap
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 16:58:00 2006
     */
    public function RemoveCronFromCategoryMap($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql="DELETE FROM cron_category_map WHERE cronID='".$nCronID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nCronID,
            "type" => "cron_category_edit",
            "action" => __METHOD__,
            "comment" => "Removed Cron ID $nCronID from all categories"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
        
    }
    /**
     * SetCronEnabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronEnabled($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="UPDATE cronjob SET
            active=1,
            delayed_until='',
            last_ranenabled=".time()."
            WHERE ID='".$nCronID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCronID,
                "type" => "cron_edit",
                "action" => __METHOD__,
                "comment" => "Enabled Cron $nCronID"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetCronMonitoringEnabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronMonitoringEnabled($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="UPDATE cronjob SET
                ignoreMonitor=0,
                delayed_until='',
                last_ranenabled=".time()."
                WHERE ID='".$nCronID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCronID,
                "type" => "cron_edit",
                "action" => __METHOD__,
                "comment" => "Enabled Cron MONITORING on $nCronID"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetCronDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronDisabled($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="UPDATE cronjob SET
                active=0,
                delayed_until='',
                mon_currentlevel=0,
                mon_currentlevelstart=0,
                mon_lastcheck=0
                WHERE ID='".$nCronID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCronID,
                "type" => "cron_edit",
                "action" => __METHOD__,
                "comment" => "Disabled Cron $nCronID"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetCronDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronMonitoringDisabled($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="UPDATE cronjob SET
                ignoreMonitor=1,
                delayed_until='',
                mon_currentlevel=0,
                mon_currentlevelstart=0,
                mon_lastcheck=0
                WHERE ID='".$nCronID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCronID,
                "type" => "cron_edit",
                "action" => __METHOD__,
                "comment" => "Disabled Cron MONITORING on $nCronID"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetCronLastRunToEmpty
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:09:43 2006
     */
    public function SetCronLastRunToEmpty($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="UPDATE cronjob SET
                last_ranstart=0,
                last_ranend=0
                WHERE ID='".$nCronID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nCronID,
                "type" => "cron_edit",
                "action" => __METHOD__,
                "comment" => "Cleared last run time to empty, cronID $nCronID"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * RemoveCron
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:12:33 2006
     */
    public function RemoveCron($nCronID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0)
        {
            $sql="DELETE FROM cronjob WHERE ID='".$nCronID."'";
            $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
            
            $this->RemoveCronFromCategoryMap($nCronID);
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nCronID,
                    "type" => "cron_edit",
                    "action" => __METHOD__,
                    "comment" => "Removed CronID $nCronID"
                );
                $this->Audit->SetAudit($aOptions, "crontab");
            }
        }
            
    }
    /**
     * SetCronEnabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronEnabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCatID >0)
        {
            $sql="SELECT cronID FROM cron_category_map WHERE categoryID='".$nCatID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $row)
                {
                    $aCronID[] = $row["cronID"];
                    
                    $aOptions=array(
                        "primaryNumericID" => $row["cronID"],
                        "type" => "cron_edit",
                        "action" => __METHOD__,
                        "comment" => "Enabled Cron in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                    );
                    $this->Audit->SetAudit($aOptions, "crontab");
                }
                $sql="UPDATE cronjob SET
                    active=1,
                    delayed_until='',
                    last_ranenabled=".time()."
                    WHERE ID IN (".join($aCronID, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Enabled Crons in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                );
                $this->Audit->SetAudit($aOptions, "crontab");

            }
        }
    }
    /**
     * SetCronMonitoringEnabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronMonitoringEnabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCatID >0)
        {
            $sql="SELECT cronID FROM cron_category_map WHERE categoryID='".$nCatID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $row)
                {
                    $aCronID[] = $row["cronID"];
                    
                    $aOptions=array(
                        "primaryNumericID" => $row["cronID"],
                        "type" => "cron_edit",
                        "action" => __METHOD__,
                        "comment" => "Enabled Cron MONITORING in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                    );
                    $this->Audit->SetAudit($aOptions, "crontab");
                }
                $sql="UPDATE cronjob SET
                    ignoreMonitor=0, delayed_until='',
                    last_ranenabled=".time()."
                    WHERE ID IN (".join($aCronID, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Enabled Cron MONITORING in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                );
                $this->Audit->SetAudit($aOptions, "crontab");

            }
        }
    }
    /**
     * SetCronDisabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronDisabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCatID >0)
        {
            $sql="SELECT cronID FROM cron_category_map WHERE categoryID='".$nCatID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $row)
                {
                    $aCronID[] = $row["cronID"];
                    
                    $aOptions=array(
                        "primaryNumericID" => $row["cronID"],
                        "type" => "cron_edit",
                        "action" => __METHOD__,
                        "comment" => "Disabled Cron in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                    );
                    $this->Audit->SetAudit($aOptions, "crontab");
                }
                $sql="UPDATE cronjob SET
                    active=0,
                    delayed_until='',
                    mon_currentlevel=0,
                    mon_currentlevelstart=0,
                    mon_lastcheck=0
                    WHERE ID IN (".join($aCronID, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Disabled Crons in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                );
                $this->Audit->SetAudit($aOptions, "crontab");

            }
        }
    }
    /**
     * SetCronMonitoringDisabledByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronMonitoringDisabledByCategory($nCatID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCatID >0)
        {
            $sql="SELECT cronID FROM cron_category_map WHERE categoryID='".$nCatID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $row)
                {
                    $aCronID[] = $row["cronID"];
                    
                    $aOptions=array(
                        "primaryNumericID" => $row["cronID"],
                        "type" => "cron_edit",
                        "action" => __METHOD__,
                        "comment" => "Disabled Cron MONITORING in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                    );
                    $this->Audit->SetAudit($aOptions, "crontab");
                }
                $sql="UPDATE cronjob SET
                    ignoreMonitor=1,
                    delayed_until='',
                    mon_currentlevel=0,
                    mon_currentlevelstart=0,
                    mon_lastcheck=0
                    WHERE ID IN (".join($aCronID, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Disabled Cron MONITORING in Category $nCatID (CronIDs: ".join($aCronID, ",").")"
                );
                $this->Audit->SetAudit($aOptions, "crontab");

            }
        }
    }
    /**
     * SetCronDelayed
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronDelayed($nCronID, $nDelayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCronID >0 && $nDelayUntil > time())
        {
            $sql="UPDATE cronjob SET
                active=2,
                delayed_until='".$nDelayUntil."'
                WHERE ID='".$nCronID."'";
            db_query($sql);
        }
        
        $aOptions=array(
            "primaryNumericID" => $nCronID,
            "type" => "cron_edit",
            "action" => __METHOD__,
            "comment" => "Delayed Cron $nCronID until UNIX_TIMESTAMP $nDelayUntil"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronDelayedByCategory
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:06:37 2006
     */
    public function SetCronDelayedByCategory($nCatID, $delayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nCatID >0 && $delayUntil>time())
        {
           $sql="SELECT m.cronID
            FROM cron_category_map m
            LEFT JOIN cronjob c ON c.ID=m.cronID
            WHERE c.active=1
                AND m.categoryID='".$nCatID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $row)
                {
                    $aCronID[] = $row["cronID"];
                    
                    $aOptions=array(
                        "primaryNumericID" => $row["cronID"],
                        "type" => "cron_edit",
                        "action" => __METHOD__,
                        "comment" => "Delayed Crons in Category $nCatID (CronIDs: ".join($aCronID, ",").") until UNIX_TIMESTAMP $delayUntil"
                    );
                    $this->Audit->SetAudit($aOptions, "crontab");
                    
                }
                $sql="UPDATE cronjob SET
                    active=2,
                    delayed_until='".$delayUntil."'
                    WHERE ID IN (".join($aCronID, ",").")";
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nCatID,
                    "type" => "cron_category_edit",
                    "action" => __METHOD__,
                    "comment" => "Delayed Crons in Category $nCatID (CronIDs: ".join($aCronID, ",").") until UNIX_TIMESTAMP $delayUntil"
                );
                $this->Audit->SetAudit($aOptions, "crontab");

            }
        }
    }
    /**
     * SetCronGlobalStatusNormal
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:28:55 2006
     */
    public function SendEmailOnIncidentCommentAdd($nIncidentID, $sUsername, $nCommentID, $sComment)
    {
        $BigDaddyData = new BigDaddyData();
        
        //Getting incident stuff
        $aIncident = $BigDaddyData->GetIncidentByID($nIncidentID);
        
        $parseini=new ParseIni("incident");
		$globalSettings=$parseini->read_inifile();
        
        if ($globalSettings["email"]["commentadd"]!="")
        {
            //We are expecting tags
            $aTags = $BigDaddyData->GetPhoneTags();
            foreach ($aTags as $aRow)
            {
                $aUseTags[$aRow["ID"]] = $aRow["phoneNumber"];
            }
            
            //split the string on commas
            $aSendEmail = explode(",", $globalSettings["email"]["incidentadd"]);
            
            $aHeaders[] = "From: ".EMAIL_FROM;
            
            $sSubject = "Incident Report: Comment Added";
            $sBody = "New Incident Comment Added on: {$aIncident["title"]}
Comment By: $sUsername
http://".$_SERVER["HTTP_HOST"]."/incident/?page=IncidentView&ID=$nIncidentID

$sComment
";
            
            if (is_array($aSendEmail))
            {
                foreach ($aSendEmail as $sTag)
                {
                    mail($aUseTags[$sTag], $sSubject, $sBody, join($aHeaders, "\r\n"));
                }
            }
        }
		$aOptions=array(
            "primaryNumericID" => $nIncidentID,
            "secondaryNumericID" => $nIncidentID,
            "type" => "incident-edit",
            
            "action" => __METHOD__,
            "comment" => "Sent"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronGlobalStatusNormal
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:28:55 2006
     */
    public function SendEmailOnIncidentAdd($sIncidentTitle, $nIncidentID)
    {
        $BigDaddyData = new BigDaddyData();
        $parseini=new ParseIni("incident");
		$globalSettings=$parseini->read_inifile();
        
        if ($globalSettings["email"]["incidentadd"]!="")
        {
            //We are expecting tags
            $aTags = $BigDaddyData->GetPhoneTags();
            foreach ($aTags as $aRow)
            {
                $aUseTags[$aRow["ID"]] = $aRow["phoneNumber"];
            }
            
            //split the string on commas
            $aSendEmail = explode(",", $globalSettings["email"]["incidentadd"]);
            
            $aHeaders[] = "From: ".EMAIL_FROM;
            
            $sSubject = "Incident Report: New Report Added";
            $sBody = "New Incident Report Added: $sIncidentTitle
http://".$_SERVER["HTTP_HOST"]."/incident/?page=IncidentView&ID=$nIncidentID";
            
            if (is_array($aSendEmail))
            {
                foreach ($aSendEmail as $sTag)
                {
                    mail($aUseTags[$sTag], $sSubject, $sBody, join($aHeaders, "\r\n"));
                }
            }
        }
		$aOptions=array(
            "primaryNumericID" => $nIncidentID,
            "type" => "incident-edit",
            
            "action" => __METHOD__,
            "comment" => "Sent Email on Incident Add to Incident $nIncidentID"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronGlobalStatusNormal
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:28:55 2006
     */
    public function SetCronGlobalStatusNormal()
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $parseini=new ParseIni("crontab");
		$globalSettings=$parseini->read_inifile();

		//Now reset to normal
		$parseini->write_inivar("[global]globalstatus=on");
        $parseini->write_inivar("[global]globaldelay=0");
        $parseini->writetoDB();

		//If the status previously was off or delayed then we need to prevent monitoring from being stale.
		if ($globalSettings["global"]["globalstatus"]=="off" || $globalSettings["global"]["globalstatus"]=="delay")
		{
			$sql="UPDATE cronjob SET
                last_ranenabled=".time().",
                mon_currentlevel=0,
                mon_lastcheck=0,
                mon_currentlevelstart=0
                WHERE active=1";
			db_query($sql);
		}
        
        $aOptions=array(
            "type" => "cron_global",
            "action" => __METHOD__,
            "comment" => "Reset Status to Normal"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronGlobalStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:30:31 2006
     */
    public function SetCronGlobalStatusDisabled()
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $parseini=new ParseIni("crontab");
        $parseini->write_inivar("[global]globalstatus=off");
        $parseini->write_inivar("[global]globaldelay=0");
        $parseini->writetoDB();
        
        $aOptions=array(
            "type" => "cron_global",
            "action" => __METHOD__,
            "comment" => "Disabled all Crons Globally"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronGlobalMonitoringStatusDisabled
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:31:34 2006
     */
    public function SetCronGlobalMonitoringStatusDisabled()
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $parseini=new ParseIni("crontab");
        $parseini->write_inivar("[global]globalstatus=disablemonitoring");
        $parseini->write_inivar("[global]globaldelay=0");
        $parseini->writetoDB();
        
        $aOptions=array(
            "type" => "cron_global",
            "action" => __METHOD__,
            "comment" => "Disabled all Cron MONITORING Globally"
        );
        $this->Audit->SetAudit($aOptions, "crontab");
    }
    /**
     * SetCronGlobalStatusDelayed
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:32:53 2006
     */
    public function SetCronGlobalStatusDelayed($nDelayUntil)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nDelayUntil>time())
        {
            $parseini=new ParseIni("crontab");
            $parseini->write_inivar("[global]globalstatus=delay");
            $parseini->write_inivar("[global]globaldelay=".$delayUntil);
            $parseini->writetoDB();
            
            $aOptions=array(
                "type" => "cron_global",
                "action" => __METHOD__,
                "comment" => "Delayed all Cron Globally until UNIX_TIMESTAMP: $delayUntil"
            );
            $this->Audit->SetAudit($aOptions, "crontab");
        }
    }
    /**
     * SetIniFile
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:35:31 2006
     */
    public function SetIniFile($aInfo, $sIniID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($aInfo["name"]!="" && $aInfo["iniID"]!="")
        {
            if ($sIniID == NULL)
            {
                $iniID=trim($aInfo["iniID"]);
                $iniID=str_replace(" ", "", $iniID);
                
                $sql="INSERT INTO inifile SET
                    name='".htmlspecialchars($aInfo["name"])."',
                    ID='".$iniID."',
                    inifile='".$aInfo["inifile"]."'";
                db_query($sql);
                
                $aOptions=array(
                    "primaryStringID" => $iniID,
                    "type" => "meta_edit",
                    "action" => __METHOD__,
                    "comment" => "Added New INI $iniID with name ".$aInfo["name"]
                );
                $this->Audit->SetAudit($aOptions, "meta");
            }
            else
            {
                $sql="UPDATE inifile SET
                    name='".htmlspecialchars($aInfo["name"])."',
                    inifile='".$aInfo["inifile"]."'
                    WHERE ID='".$sIniID."'";
                db_query($sql);
                
                $aOptions=array(
                    "primaryStringID" => $sIniID,
                    "type" => "meta_edit",
                    "action" => __METHOD__,
                    "comment" => "Updated INI $sIniID with info: ".print_r($aInfo, true)
                );
                $this->Audit->SetAudit($aOptions, "meta");
            }
            
        }
        
    }
    /**
     * RemoveIniFile
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:41:32 2006
     */
    public function RemoveIniFile($sIniID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($sIniID!="")
        {
            $sql="DELETE FROM inifile WHERE ID='".$sIniID."'";
            db_query($sql);
            
            $sql="UPDATE cronjob SET iniID='' WHERE iniID='".$sIniID."'";
            db_query($sql);
			
			$sql="UPDATE monitoring SET iniID='' WHERE iniID='".$sIniID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryStringID" => $sIniID,
                "type" => "meta_edit",
                "action" => __METHOD__,
                "comment" => "Removed IniID ID $sIniID"
            );
            $this->Audit->SetAudit($aOptions, "meta");
        }
    }
    /**
     * SetModule
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:46:40 2006
     */
    public function SetModule($aInfo, $nModuleID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($aInfo["name"]!="" && $aInfo["filename"]!=""
            && $aInfo["runfrom"]!="" && $aInfo["distribute"]!="" && $aInfo["type"]!="")
        {
            if ($nModuleID == NULL)
            {
                $sql="INSERT INTO module SET
                name='".htmlspecialchars($aInfo["name"])."',
                filename='".$aInfo["filename"]."',
                notes='".htmlspecialchars($aInfo["notes"])."',
                distribute='".$aInfo["distribute"]."',
                type='".$aInfo["type"]."',
                runfrom='".$aInfo["runfrom"]."'";
                $nInsertID = db_query($sql, array("getInsertID" => true));
                
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "meta_edit",
                    "action" => __METHOD__,
                    "comment" => "Added New Module $nInsertID with name ".$aInfo["name"]
                );
                $this->Audit->SetAudit($aOptions, "meta");
            }
            else
            {
                $sql="UPDATE module SET
                name='".htmlspecialchars($aInfo["name"])."',
                filename='".$aInfo["filename"]."',
                notes='".htmlspecialchars($aInfo["notes"])."',
                distribute='".$aInfo["distribute"]."',
                type='".$aInfo["type"]."',
                runfrom='".$aInfo["runfrom"]."'
                WHERE ID=".$nModuleID;
                db_query($sql);
                
                $aOptions=array(
                    "primaryNumericID" => $nModuleID,
                    "type" => "meta_edit",
                    "action" => __METHOD__,
                    "comment" => "Updated Module $nModuleID with info: ".print_r($aInfo, true)
                );
                $this->Audit->SetAudit($aOptions, "meta");
            }
        }
    }
    /**
     * RemoveModule
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Fri Oct 27 17:51:35 2006
     */
    public function RemoveModule($nModuleID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nModuleID>0)
        {
 
            $sql = "SELECT ID, serverID FROM server_module WHERE moduleID = '".$nModuleID."'";
            $aResult = db_fetch_array(db_query($sql));
            
            if (is_array($aResult))
            {
                foreach ($aResult as $aRow)
                {
                    $this->RemoveServerMod($aRow["ID"], $aRow["serverID"]);
                    $this->RemoveServerGroupModuleByModuleID($aRow["ID"]);
                    $this->RemoveReportGroupModuleByModuleID($aRow["ID"]);
                }
            }

            $sql="DELETE FROM module WHERE ID='".$nModuleID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nModuleID,
                "type" => "meta_edit",
                "action" => __METHOD__,
                "comment" => "Removed ModuleID $nModuleID"
            );
            $this->Audit->SetAudit($aOptions, "meta");
        }
    }
    /**
     * int SetReportGroup($aInfo, $nID)
     * sets a server group if ID is included it updates
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 01/06/2006 18:17:02
     */
    public function SetReportGroup($aInfo, $nID = NULL)
    {
        //if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($aInfo["groupname"] == "")
        {
            return -1;
        }
        
        $sFields = "
        groupname='".htmlspecialchars($aInfo["groupname"])."',
        notes='".htmlspecialchars($aInfo["notes"])."'";
        
        if ($nID == NULL)
        {
            $sql="INSERT INTO report_group SET
            $sFields";
            $insertID=db_query($sql, array("getInsertID" => true));
            
            $aOptions=array(
                "primaryNumericID" => $insertID,
                "type" => "reportgroup_edit",
                "action" => __METHOD__,
                "comment" => "Added New Report Group $insertID, Group name: ".$aInfo["groupname"]
            );
            $this->Audit->SetAudit($aOptions, "reportgroup");
            
            return $insertID;
        }
        else
        {
            $sql = "UPDATE report_group SET
            $sFields
            WHERE ID = '".$nID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "reportgroup_edit",
                "action" => __METHOD__,
                "comment" => "Updated Report Group $nID, Information: ".print_r($aInfo, true)
            );
            $this->Audit->SetAudit($aOptions, "reportgroup");
        }
    }
    /**
     * int SetServerGroup($aInfo, $nID)
     * sets a server group if ID is included it updates
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 01/06/2006 18:17:02
     */
    public function SetServerGroup($aInfo, $nID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($aInfo["groupname"] == "")
        {
            return -1;
        }
        
        $sFields = "
        groupname='".htmlspecialchars($aInfo["groupname"])."',
		iniID='".$aInfo["iniID"]."',
		mon_startlevel='".$aInfo["mon_startlevel"]."',
        mon_percentthreshold = '".$aInfo["mon_percentthreshold"]."',
        mon_numberthreshold = '".$aInfo["mon_numberthreshold"]."',
		mon_endlevel='".$aInfo["mon_endlevel"]."',
        notes='".htmlspecialchars($aInfo["notes"])."'";
        
        if ($nID == NULL)
        {
            $sql="INSERT INTO server_group SET
            $sFields";
            $insertID=db_query($sql, array("getInsertID" => true));
            
            $aOptions=array(
                "primaryNumericID" => $insertID,
                "type" => "servergroup_edit",
                "action" => __METHOD__,
                "comment" => "Added New Server Group $insertID, Group name: ".$aInfo["groupname"]
            );
            $this->Audit->SetAudit($aOptions, "servergroup");
            
            return $insertID;
        }
        else
        {
            $sql = "UPDATE server_group SET
            $sFields
            WHERE ID = '".$nID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "servergroup_edit",
                "action" => __METHOD__,
                "comment" => "Updated Server Group $nID, Information: ".print_r($aInfo, true)
            );
            $this->Audit->SetAudit($aOptions, "servergroup");
        }
    }
    /**
     * int SetServerGroupModule($nServerModuleID, $nServerGroupID)
     * sets a server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 01/06/2006 19:04:44
     */
    public function SetServerGroupModule($nServerModuleID, $nServerGroupID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if (!$nServerGroupID || !$nServerModuleID)
        {
            return -1;
        }
        
        $this->RemoveServerGroupModule($nServerModuleID, $nServerGroupID);
        
        
        $sql = "INSERT INTO server_group_map SET
            server_moduleID = '".$nServerModuleID."',
            server_groupID = '".$nServerGroupID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nServerGroupID,
            "secondaryNumericID" => $nServerModuleID,
            "type" => "servergroup_edit",
            "action" => __METHOD__,
            "comment" => "Added ServerModuleID $nServerModuleID to ServerGroup $nServerGroupID"
        );
        $this->Audit->SetAudit($aOptions, "servergroup");

    }
    /**
     * int SetReportGroupModule($nServerModuleID, $nServerGroupID)
     * sets a server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 01/06/2006 19:04:44
     */
    public function SetReportGroupModule($nServerModuleID, $nReportGroupID)
    {
        //if (!$this->IsUserAllowed(__METHOD__)) return;
        if (!$nReportGroupID || !$nServerModuleID)
        {
            return -1;
        }
        
        $this->RemoveReportGroupModule($nServerModuleID, $nReportGroupID);
        
        
        $sql = "INSERT INTO report_group_map SET
            server_moduleID = '".$nServerModuleID."',
            report_groupID = '".$nReportGroupID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nReportGroupID,
            "secondaryNumericID" => $nServerModuleID,
            "type" => "reportgroup_edit",
            "action" => __METHOD__,
            "comment" => "Added ServerModuleID $nServerModuleID to ReportGroup $nReportGroupID"
        );
        $this->Audit->SetAudit($aOptions, "reportgroup");

    }
    
    /**
     * void RemoveServerGroupModuleByModuleID($nServerModuleID, $nServerGroupID)
     * removes a particular server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:30:59
     */
    public function RemoveServerGroupModuleByModuleID($nServerModuleID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql = "DELETE FROM server_group_map
            WHERE server_moduleID = '".$nServerModuleID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows > 0)
        {
            $aOptions=array(
                "primaryNumericID" => $nServerModuleID,
                "type" => "servergroupmod_edit",
                "action" => __METHOD__,
                "comment" => "Removed ModuleID: $nServerModuleID from all serverGroups  $nServerGroupID"
            );
            $this->Audit->SetAudit($aOptions, "servergroup");
        }
        
        return;
    }
    /**
     * void RemoveServerGroupModuleByModuleID($nServerModuleID, $nServerGroupID)
     * removes a particular server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:30:59
     */
    public function RemoveReportGroupModuleByModuleID($nServerModuleID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql = "DELETE FROM report_group_map
            WHERE server_moduleID = '".$nServerModuleID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows > 0)
        {
            $aOptions=array(
                "primaryNumericID" => $nServerModuleID,
                "type" => "reportgroupmod_edit",
                "action" => __METHOD__,
                "comment" => "Removed ModuleID: $nServerModuleID from all reportGroups  $nServerGroupID"
            );
            $this->Audit->SetAudit($aOptions, "reportgroup");
        }
        
        return;
    }
    /**
     * void RemoveServerGroupModule($nServerModuleID, $nServerGroupID)
     * removes a particular server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:30:59
     */
    public function RemoveReportGroupModule($nServerModuleID, $nReportGroupID)
    {
        //if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql = "DELETE FROM report_group_map
            WHERE server_moduleID = '".$nServerModuleID."'
                AND report_groupID = '".$nReportGroupID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows > 0)
        {
            $aOptions=array(
                "primaryNumericID" => $nReportGroupID,
                "secondaryNumericID" => $nServerModuleID,
                "type" => "servergroup_edit",
                "action" => __METHOD__,
                "comment" => "Removed ModuleID: $nServerModuleID from reportGroupID  $nReportGroupID"
            );
            $this->Audit->SetAudit($aOptions, "reportgroup");
        }
        
        return;
    }
    /**
     * void RemoveServerGroupModule($nServerModuleID, $nServerGroupID)
     * removes a particular server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:30:59
     */
    public function RemoveServerGroupModule($nServerModuleID, $nServerGroupID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql = "DELETE FROM server_group_map
            WHERE server_moduleID = '".$nServerModuleID."'
                AND server_groupID = '".$nServerGroupID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows > 0)
        {
            $aOptions=array(
                "primaryNumericID" => $nServerGroupID,
                "secondaryNumericID" => $nServerModuleID,
                "type" => "servergroup_edit",
                "action" => __METHOD__,
                "comment" => "Removed ModuleID: $nServerModuleID from serverGroupID  $nServerGroupID"
            );
            $this->Audit->SetAudit($aOptions, "reportgroup");
        }
        
        return;
    }
    /**
     * void RemoveServerGroupModuleByModuleID($nServerModuleID, $nServerGroupID)
     * removes a particular server group module
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:30:59
     */
    public function RemoveServerGroupModuleByServerID($nServerID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        
        $sql = "SELECT ID FROM server_module WHERE serverID = '".$nServerID."'";
        $aResult = db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            foreach ($aResult as $aRow)
            {
                $this->RemoveServerGroupModuleByModuleID($aRow["ID"]);
            }
        }
        
        $aOptions=array(
            "primaryNumericID" => $nServerID,
            "type" => "server_edit",
            "action" => __METHOD__,
            "comment" => "Removed Modules related to $nServerID from all server groups"
        );
        $this->Audit->SetAudit($aOptions, "servergroup");
        
        return;
    }
    /**
     * void SetServerGroupStatusToEnabled($nID)
     * sets the status of a particular server group
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:36:24
     */
    public function SetServerGroupStatusToEnabled($nID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql="UPDATE server_group SET active=1, last_monenabled=".time()."
        WHERE ID='".$nID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nID,
            "type" => "servergroup_edit",
            "action" => __METHOD__,
            "comment" => "Enabled Server Group $nID"
        );
        $this->Audit->SetAudit($aOptions, "servergroup");
    }
    /**
     * void SetServerGroupStatusToDisabled($nID)
     * sets the status of a particular server group
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:36:24
     */
    public function SetServerGroupStatusToDisabled($nID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql="UPDATE server_group SET active=0, mon_currentlevel=0,
            mon_currentlevelstart=0, mon_lastcheck=0
            WHERE ID='".$nID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nID,
            "type" => "servergroup_edit",
            "action" => __METHOD__,
            "comment" => "Disabled Server Group $nID"
        );
        $this->Audit->SetAudit($aOptions, "servergroup");
    }
    /**
     * void RemoveServerGroup($nID)
     * removed a server group and associations
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:43:08
     */
    public function RemoveServerGroup($nID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql="DELETE FROM server_group WHERE ID='".$nID."'";
        db_query($sql);
            
        $sql="DELETE FROM server_group_map WHERE server_groupID='".$nID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nID,
            "type" => "servergroup_edit",
            "action" => __METHOD__,
            "comment" => "Removed ServergroupID $nID"
        );
        $this->Audit->SetAudit($aOptions, "servergroup");
    }
    /**
     * void RemoveServerGroup($nID)
     * removed a server group and associations
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 10:43:08
     */
    public function RemoveReportGroup($nID)
    {
        //if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql="DELETE FROM report_group WHERE ID='".$nID."'";
        db_query($sql);
            
        $sql="DELETE FROM report_group_map WHERE report_groupID='".$nID."'";
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nID,
            "type" => "reportgroup_edit",
            "action" => __METHOD__,
            "comment" => "Removed ReportgroupID $nID"
        );
        $this->Audit->SetAudit($aOptions, "reportgroup");
    }
    /**
     * void SetServerGroupDelay($nServerGroupID, $nUnixTimeStamp)
     * Sets a delay on monitoring for a server group
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version 02/06/2006 11:29:33@version 02/06/2006 11:29:33
     */
    public function SetServerGroupDelay($nServerGroupID, $nUnixTimeStamp)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nUnixTimeStamp>time())
        {
            $sql="UPDATE server_group SET active=2, delayed_until='".$nUnixTimeStamp."'
            WHERE ID='".$nServerGroupID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nServerGroupID,
                "type" => "servergroup_edit",
                "action" => __METHOD__,
                "comment" => "Delayed ServerGroup $nServerGroupID until UNIX_TIMESTAMP $nUnixTimeStamp"
            );
            $this->Audit->SetAudit($aOptions, "servergroup");
            
        }
    }
    /**
     * SetPhoneTag
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 10:18:14 2006
     */
    public function SetPhoneTag($aInfo, $sTagID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($sTagID == NULL)
        {
            //Remove any spaces and make it all lower case
            $sID = str_replace(" ","",$aInfo["ID"]);
            $sID = strtolower($sID);
            
            $sql = "INSERT INTO phoneTag SET
                ID = '".$sID."',
                phoneNumber = '".$aInfo["phoneNumber"]."',
                notes = '".$aInfo["notes"]."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryStringID" => $sID,
                "type" => "meta_admin",
                "action" => __METHOD__,
                "comment" => "Added new phone tag with ID $sID"
            );
            $this->Audit->SetAudit($aOptions, "meta");
  
        }
        else
        {
            //Remove any spaces and make it all lower case
            $sID = str_replace(" ","",$sTagID);
            $sID = strtolower($sID);
            
            $sql = "UPDATE phoneTag SET
                phoneNumber = '".$aInfo["phoneNumber"]."',
                notes = '".$aInfo["notes"]."'
                WHERE ID = '".$sID."'";
            db_query($sql);
            
            $aOptions=array(
                "primaryStringID" => $sID,
                "type" => "meta_admin",
                "action" => __METHOD__,
                "comment" => "Updated phone tag with ID $sID"
            );
            $this->Audit->SetAudit($aOptions, "meta");
        }
    }
    /**
     * RemovePhoneTag
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 10:26:12 2006
     */
    public function RemovePhoneTag($sTagID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        $sql = "DELETE FROM phoneTag WHERE ID = '".$sTagID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows > 0)
        {
            $aOptions=array(
                "primaryStringID" => $sTagID,
                "type" => "meta_admin",
                "action" => __METHOD__,
                "comment" => "Removed phone tag with tagID $sTagID"
            );
            $this->Audit->SetAudit($aOptions, "meta");
        }
    }
    /**
     * SetIncident
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    public function SetIncident($aInfo, $nIncidentID = NULL)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        if ($nIncidentID == NULL)
        {
            
            $sql = "INSERT INTO incident SET
                incidentStart = '".$aInfo["incidentStart"]."',
                incidentEnd = '".$aInfo["incidentEnd"]."',
                postedBy = '".LOGGEDIN_USERNAME."',
                postedTime = '".time()."',
                title = '".db_escape_string($aInfo["title"])."',
                description = '".db_escape_string($aInfo["description"])."',
                reasons = '".db_escape_string($aInfo["reasons"])."',
                followup = '".db_escape_string($aInfo["followup"])."'";
            $nInsertID = db_query($sql, array("getInsertID" => true));
            
            //Send array of Servers to be mapped
            $this->SetIncidentServer($aInfo["aServerID"], $nInsertID);
            
            //Send an email
            $this->SendEmailOnIncidentAdd($aInfo["title"], $nInsertID);
            
            $aOptions=array(
                "primaryNumericID" => $nInsertID,
                "type" => "incident-edit",
                "action" => __METHOD__,
                "comment" => "Added new Incident with ID $nInsertID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
  
        }
        else
        {
            
            $sql = "UPDATE incident SET
                incidentStart = '".$aInfo["incidentStart"]."',
                incidentEnd = '".$aInfo["incidentEnd"]."',
                title = '".db_escape_string($aInfo["title"])."',
                description = '".db_escape_string($aInfo["description"])."',
                reasons = '".db_escape_string($aInfo["reasons"])."',
                followup = '".db_escape_string($aInfo["followup"])."'
                WHERE ID = '".$nIncidentID."'";
            db_query($sql);
            
            //Send array of Servers to be mapped
            $this->RemoveIncidentServer($nIncidentID);
            $this->SetIncidentServer($aInfo["aServerID"], $nIncidentID);
            
            $aOptions=array(
                "primaryNumericID" => $nIncidentID,
                "type" => "incident-edit",
                "action" => __METHOD__,
                "comment" => "Updated Incident with ID $nIncidentID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
        }
    }
    /**
     * SetIncidentComment
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    public function SetIncidentComment($aInfo, $nIncidentID, $nCommentID = NULL)
    {
        
        
        //Get the Incident Comment and see who wrote it
        if ($nCommentID != NULL && !$this->IsIncidentCommentPosterLoggedIn($nCommentID) && !$this->IsUserAllowed(__METHOD__))
        {
                return;
        }
        
        
        
        if ($nCommentID == NULL)
        {
            
            $sql = "INSERT INTO incidentComment SET
                incidentID = '".$nIncidentID."',
                postedBy = '".LOGGEDIN_USERNAME."',
                postedTime = '".time()."',
                comment = '".db_escape_string($aInfo["comment"])."'";
            $nInsertID = db_query($sql, array("getInsertID" => true));
            
            $this->SendEmailOnIncidentCommentAdd($nIncidentID, LOGGEDIN_USERNAME, $nInsertID, $aInfo["comment"]);
            
            $aOptions=array(
                "primaryNumericID" => $nIncidentID,
                "secondaryNumericID" => $nInsertID,
                "type" => "incident-comment",
                "action" => __METHOD__,
                "comment" => "Added new Comment ($nInsertID) to Incident with ID $nInsertID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
  
        }
        else
        {
            
            $sql = "UPDATE incidentComment SET
                comment = '".db_escape_string($aInfo["comment"])."'
                WHERE ID = '".$nCommentID."'";
           
            db_query($sql);
            
            $aOptions=array(
                "primaryNumericID" => $nIncidentID,
                "secondaryNumericID" => $nCommentID,
                "type" => "incident-comment",
                "action" => __METHOD__,
                "comment" => "Updated Comment ($nCommentID) to Incident with ID $nIncidentID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
        }
    }
    /**
     * SetIncidentServer
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    private function SetIncidentServer($aServerID, $nIncidentID)
    {
        if (is_array($aServerID))
        {
            foreach ($aServerID as $nServerID)
            {
                $sql = "INSERT INTO incidentServer SET
                    serverID = '".$nServerID."',
                    incidentID = '".$nIncidentID."'";
                db_query($sql);
            }
            
            $aOptions=array(
                "primaryNumericID" => $nIncidentID,
                "type" => "incident-edit",
                "action" => __METHOD__,
                "comment" => "Added Servers (".join($aServerID, ", ").") to Incident with ID $nIncidentID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
        }
    }
    /**
     * SetIncidentServer
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    private function RemoveIncidentServer($nIncidentID)
    {
        $sql = "DELETE FROM incidentServer
            WHERE incidentID = '".$nIncidentID."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows >0)
        {
            $aOptions=array(
                "primaryNumericID" => $nIncidentID,
                "type" => "incident-edit",
                "action" => __METHOD__,
                "comment" => "Removed mapped servers for incident with ID $nIncidentID"
            );
            $this->Audit->SetAudit($aOptions, "incident");
        }
    }
    /**
     * RemoveIncident
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    public function RemoveIncident($nIncidentID)
    {
        if (!$this->IsUserAllowed(__METHOD__)) return;
        
        $sql = "DELETE FROM incident
            WHERE ID = '".$nIncidentID."'";
        db_query($sql);
        
        $sql = "DELETE FROM incidentComment
            WHERE incidentID = '".$nIncidentID."'";
        db_query($sql);
        
        $this->RemoveIncidentServer($nIncidentID);
        
        $aOptions=array(
            "primaryNumericID" => $nIncidentID,
            "type" => "incident-edit",
            "action" => __METHOD__,
            "comment" => "Removed incident with ID $nIncidentID"
        );
        $this->Audit->SetAudit($aOptions, "incident");
        
        
    }
    /**
     * RemoveIncidentComment
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    public function RemoveIncidentComment($nCommentID, $nIncidentID)
    {
        //Get the Incident Comment and see who wrote it
        if ($nCommentID != NULL && !$this->IsIncidentCommentPosterLoggedIn($nCommentID) && !$this->IsUserAllowed(__METHOD__))
        {
                return;
        }
        
        $sql = "DELETE FROM incidentComment
            WHERE ID = ".$nCommentID;
        db_query($sql);
        
        $aOptions=array(
            "primaryNumericID" => $nIncidentID,
            "secondaryNumericID" => $nCommentID,
            "type" => "incident-comment",
            "action" => __METHOD__,
            "comment" => "Removed Comment ($nCommentID) to Incident with ID $nIncidentID"
        );
        $this->Audit->SetAudit($aOptions, "incident");
    }
    /**
     * RemoveIncidentComment
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 30 19:39:46 2006
     */
    private function IsIncidentCommentPosterLoggedIn($nCommentID)
    {
        $sql = "SELECT postedBy
            FROM incidentComment
            WHERE ID = '".$nCommentID."'";
        $aResult = db_fetch_result(db_query($sql));
        
        if ($aResult["postedBy"] == LOGGEDIN_USERNAME)
        {
            return true;
        }
        
        return false;
    }
    /**
     * SetCronStart
     * Sets the cron start if such is available
     * @author Duleepa Wijayawardhana <dups@dups.ca>
     * @param cronID
     * @return void
     */
    public function SetCronStart($cronID)
    {
        $sql="UPDATE cronjob SET last_ranstart=".time()." WHERE ID='".$cronID."'";
        db_query($sql);
    }
    /**
     * SetCronEnd
     * Sets the cron End
     * @author Duleepa Wijayawardhana <dups@dups.ca>
     * @param cronID
     * @return void
     */
    public function SetCronEnd($cronID)
    {
        $timeupdate=time();
        
        $sql = "SELECT last_ranstart FROM cronjob WHERE ID='".$cronID."'";
        $aResult = db_fetch_result(db_query($sql));
        
        $nStart = $aResult['last_ranstart'];
        
        $sql="UPDATE cronjob SET last_ranend=".$timeupdate.", last_ranenabled=".$timeupdate." WHERE ID='".$cronID."'";
        db_query($sql);
           
        $sql = "INSERT IGNORE INTO cronHistory SET
            last_ranstart = '".$nStart."',
            last_ranend = '".$timeupdate."',
            time_elapsed = '".($timeupdate - $nStart)."',
            cronID = '".$cronID."'";
        db_query( $sql, array("dbHandle" => "bigdaddystats") );
    }
    /**
     * SetCronLog
     * Sets the cron Log
     * @author Duleepa Wijayawardhana <dups@dups.ca>
     * @param cronID
     * @return void
     */
    public function SetCronLog($cronID, $sText)
    {
        $sql="INSERT IGNORE INTO cronLog (logEntryTimestamp, cronID, logEntry)
            VALUES ('".time()."', '".$cronID."', '".db_escape_string($sText)."')";
        db_query( $sql, array("dbHandle" => "bigdaddystats") );
    }
    /**
     * GetCronStatus
     * Gets the status of a cron
     * @author Duleepa Wijayawardhana <dups@dups.ca>
     * @param cronID
     * @return bool
     */
    public function GetCronStatus($cronID, $sOptions=NULL)
    {
        $parseini= new ParseIni("crontab");
        $globalSettings=$parseini->read_inifile();
        if ($globalSettings["global"]["globalstatus"]=="off")
        {
            return false;
        }
        if ($globalSettings["global"]["globalstatus"]=="delay" && $globalSettings["global"]["globaldelay"]>time())
        {
            return false;
        }
        
        #Check to see if this particular Cron is disabled or delayed
        $sql="SELECT active, delayed_until, last_ranstart, last_ranend  FROM cronjob WHERE ID='".$cronID."'";
        $aResult = db_fetch_result(db_query($sql));
    
        if ($aResult['active'] == 0)
        {
            return false;
        }
        
        if ($aResult['active']==2 && $aResult['delayed_until']>time())
        {
            return false;
        }
        
        if ($sOptions == "CRON_NO_DUPLICATE_PROCESS")
        {
            if ($aResult["last_ranstart"]>0 && $aResult["last_ranend"]<$aResult["last_ranstart"])
            {
                return false;
            }
        }
        //If all the above is fine, return true
        return true;
    }
    
}
?>
